import React from 'react'

const EquityChart = ({ history, width = 260, height = 70 }) => {
  if (!history || history.length < 2) {
    return (
      <div style={{
        padding: '10px 14px',
        borderRadius: 12,
        border: '1px solid rgba(255,255,255,0.06)',
        background: 'rgba(255,255,255,0.02)',
        color: 'rgba(255,255,255,0.5)',
        fontSize: 12
      }}>
        收益曲线将出现在这里
      </div>
    )
  }

  const values = history.map(item => item.equity)
  const timestamps = history.map(item => item.timestamp)
  const startValue = values[0]
  const endValue = values[values.length - 1]
  const totalReturn = ((endValue - startValue) / startValue) * 100
  const min = Math.min(...values)
  const max = Math.max(...values)
  const range = max - min || 1
  // 添加内边距，防止曲线超出边界
  const paddingX = 2
  const paddingY = 2
  const chartWidth = width - paddingX * 2
  const chartHeight = height - paddingY * 2
  const points = values.map((value, index) => {
    const x = paddingX + (index / (values.length - 1)) * chartWidth
    const normalized = (value - min) / range
    const y = paddingY + chartHeight - normalized * chartHeight
    return `${x},${y}`
  }).join(' ')

  return (
    <div style={{
      padding: '12px 16px',
      borderRadius: 12,
      border: '1px solid rgba(255,255,255,0.06)',
      background: 'rgba(255,255,255,0.04)',
      display: 'flex',
      flexDirection: 'column',
      gap: 8,
      width: '100%',
      boxSizing: 'border-box'
    }}>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
        <span style={{color: '#FFFFFF', fontSize: 13}}>收益曲线</span>
        <span style={{color: totalReturn >= 0 ? '#0dd697' : '#f44336', fontSize: 13}}>
          {totalReturn.toFixed(2)}%
        </span>
      </div>
      <div style={{width: '100%', overflow: 'hidden'}}>
      <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={{display: 'block'}}>
        <defs>
          <linearGradient id="equityGradient" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="rgba(13,214,151,0.35)" />
            <stop offset="100%" stopColor="rgba(13,214,151,0)" />
          </linearGradient>
        </defs>
        <polyline
          points={points}
          fill="none"
          stroke="rgba(13,214,151,0.65)"
          strokeWidth="2"
        />
        <polygon
          points={`${points} ${width - paddingX},${height - paddingY} ${paddingX},${height - paddingY}`}
          fill="url(#equityGradient)"
        />
      </svg>
      </div>
      <div style={{display: 'flex', justifyContent: 'space-between', color: 'rgba(255,255,255,0.45)', fontSize: 11}}>
        <span>{new Date(timestamps[0]).toLocaleDateString()}</span>
        <span>{new Date(timestamps[timestamps.length - 1]).toLocaleDateString()}</span>
      </div>
    </div>
  )
}

export default EquityChart
